package _01_动态数组;

import java.util.HashMap;
import java.util.Map;

public class 剑指OfferII_010和为k的子数组 {

    public static void main(String[] args) {

        剑指OfferII_010和为k的子数组 v = new 剑指OfferII_010和为k的子数组();

        int[] nums = {1, -1, 0};

        System.out.println(v.subarraySum(nums, 0));

    }

    // 前缀和法，使用HashMap保存前缀和
    public int subarraySum(int[] nums, int k) {
        // 保存前缀和的Map
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int count = 0;
        int total = 0;
        // 遍历数组，并且保存前缀和
        for (int num : nums) {
            total += num;
            // 获取当前的前缀和
            count += map.getOrDefault(total - k, 0);
            // 保存当前前缀和
            map.put(total, map.getOrDefault(total, 0) + 1);
        }
        return count;
    }


    // 遍历法， O(n^2)
    public int subarraySum1(int[] nums, int k) {
        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            total += calculator(nums, i, k);
        }
        return total;
    }

    public int calculator(int[] nums, int begin, int target) {
        int res = 0;
        for (int i = begin; i < nums.length; i++) {
            if (nums[i] == target) {
                res++;
            }
            target -= nums[i];
        }
        return res;
    }

}
